<template>
  <div class="bg-light mb" style="position:relative">
    <div class="tinymce-head-shade" v-if="isLook"></div>
    <div class="tinymce-box-shade" ref="conBox"  v-if="isLook"></div>
    <div class="pl pr">
      <Editor id='tinymce' v-model='tinymceHtml' :init='init'></Editor>
    </div>
    <Modal v-model="modalVd" title="视频上传">
      <div class="item-videoBox" v-for="(item, index) in uploadList" :key="index">
        <template v-if="item.status === 'finished'">
          <video :src="preFixPath + item.imgUrl" controls="controls"></video>
          <Icon class="video-btn-close" type="md-close-circle" @click.native="removeUploadItem"></Icon>
        </template>
        <template v-show="item.status !== 'finished'">
          <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
        </template>
      </div>
      <Upload
        type="drag"
        ref="upload"
        :show-upload-list="false"
        :action="uploadMediaUrl"
        :accept="accept"
        :format="format"
        :headers="headers"
        :max-size="uploadMax"
        :on-format-error="onUploadFormatError"
        :on-exceeded-size="onUploadSizeError"
        :on-success="onUploadSuccess"
        v-show="uploadList.length < 1">
        <div class="ptb20">
          <Icon type="ios-cloud-upload" class="media-uploadColor" size="52"></Icon>
          <p>点击或拖拽上传视频</p>
        </div>
      </Upload>  
      <div slot="footer">
        <Button size="large"  @click="modalVd=false">取消</Button>
        <Button size="large" type="primary" @click="onSaveVd">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { uploadImageUrl, 
           uploadMediaUrl,
           preFixPath } from '@/util'
  import tinymce from 'tinymce/tinymce'
  import 'tinymce/themes/modern/theme'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  export default {
    props: {
      isLook: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        preFixPath,
        uploadImageUrl,
        uploadMediaUrl,
        headers: {},
        uploadMax: SYSTEM_CONFIG.uploadMaxSize * 1024,
        accept: SYSTEM_CONFIG.uploadMediaExtension,
        acceptImg: SYSTEM_CONFIG.uploadImageExtension,
        format: SYSTEM_CONFIG.uploadMediaExtensions,
        uploadList: [],
        modalVd: false,
        tinymceHtml: '',
        init: {
          image_dimensions: false,
          object_resizing: false,
          language_url: '//misc.hzzcckj.cn/skin/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '//misc.hzzcckj.cn/skin/tinymce/skins/lightgray',
          height: 480,
          plugins: 'link lists image code table colorpicker textcolor contextmenu ',
          toolbar:
            'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code vedio | removeformat',
      
          branding: false,
          images_upload_handler: (blobInfo, success, failure) =>{
            this.handleImgUpload(blobInfo, success, failure)
          },
          setup: (ed)=> {
            ed.addButton('vedio', {
              // title: '上传视频',
              // image: '/static/tinymce/vedio.jpg',
              icon: 'media',
              tooltip: '上传视频',
              onclick: ()=> {
                this.uploadList = []
                this.modalVd = true
              }
            })
          }
        
        }
      }
    },
    mounted () {
      tinymce.init({})
      let userToken = this.user.userToken
      if (userToken){
        this.headers['Authorization'] = 'Bearer ' + `${userToken}`
      }
      this.accept = this.accept.split(',').map(item => 'video/' + item).join(',')
    },
    computed: {
      ...mapGetters(['user'])
    },
    methods: {
      handleImgUpload(blobInfo, success, failure) {
        var xhr, formData
        xhr = new XMLHttpRequest()
        let bolb = blobInfo.blob()
        let self = this
        if (this.uploadMax > 0 && bolb.size > this.uploadMax * 1024) { //bolb.size的单位B,this.uploadMax的单位是kb
          this.$Notice.warning({
            title: '超出文件大小限制',
            desc: '文件 ' + bolb.name + ' 太大，不能超过 ' + parseInt(this.uploadMax / 1024) + 'M。'
          })
          return
        }
        if (this.acceptImg.indexOf(bolb.type.substring(6, bolb.type.length)) < 0) {
          this.$Notice.warning({
            title: '文件格式不正确',
            desc: '文件 ' + bolb.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
          })
          return
        } 
        xhr.open('post', this.uploadImageUrl)
        xhr.setRequestHeader('Authorization', 'Bearer ' + this.user.userToken)
        xhr.responseType = 'json'
        formData = new FormData()
        formData.append('file', bolb, bolb.name)
        xhr.send(formData)
        xhr.onload = function(e ) {
          let res = xhr.response
          if (typeof res === 'string') {
            res = JSON.parse(res)
          }
          if(res.code === 200){
            success(self.preFixPath + res.data.path)
          } else {
            self.$Notice.error({
              title: '上传失败',
              desc: res.message
            })
          }
        }
      },
      onSaveVd() {
        if (this.uploadList.length > 0) {
          this.tinymceHtml += `<video width="300" height="150" controls="controls"><source src="${this.preFixPath}${this.uploadList[0].imgUrl}" /></video>`
        // tinymce.get('tinymce').setContent(`<video width="300" height="150" controls="controls"><source src="${preFixPath}${this.uploadList[0].imgUrl}" /></video>`);
        }
        this.modalVd = false
      },
      onUploadSuccess(res, file) {
        if (res.code === 200) {
          file.url = res.data
          let path = res.data.path
          file.imgUrl = path
          this.$Message.success('上传成功')
          this.uploadList.push(file)
        } else {
          this.$Notice.error({
            title: '上传失败',
            desc: res.message
          })
          this.$refs.upload.fileList.splice(this.$refs.upload.fileList.length - 1, 1)
        }
      },
      removeUploadItem() {
        this.uploadList.splice(0, 1)
      },
      onUploadFormatError(file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc:
            '文件 ' + file.name + ' 格式不正确。'
        })
      },
      onUploadSizeError(file) {
        this.$Notice.warning({
          title: '超出文件大小限制',
          desc: '文件 ' + file.name + ' 太大，不能超过 ' + parseInt(this.uploadMax / 1024) + 'M。'
        })
      },
    },
    components: {
      Editor
    },
    watch: {
      tinymceHtml(newVal) {
        if (this.isLook) this.$refs.conBox.innerHTML = newVal
      }
    }
  }
</script>
